import { getToken, setToken, removeToken } from "@/utils/auth";
import fetch from "@/utils/fetch";
const user = {
  state: {
    token: getToken() || "",
    userInfo: { name: "" }
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    }
  },
  actions: {
    LogIn({ commit }, userInfo) {
      const user = userInfo.user.trim();
      const pwd = userInfo.pwd.trim();
      console.log(user, pwd);
      commit("SET_TOKEN", "6210606be56bd8d17e3f5f8137157b91ceb7043e");
      setToken("6210606be56bd8d17e3f5f8137157b91ceb7043e");
      commit("SET_USERINFO", { name: "cy" });
    },
    GetUserInfo({ commit }, token) {
      //验证token 并获取 userInfo
      return new Promise((resolve, reject) => {
        fetch({
          method: "post",
          url: "//api.chenyeah.com/blog/user/is_sign_in.php",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: `token=${token.token}`
        })
          .then(D => {
            if (D.data.code == 0) {
              commit("SET_USERINFO", D.data.data);
              resolve(D.data);
            } else {
              commit("SET_USERINFO", "");
              reject("error");
            }
          })
          .catch(e => {
            commit("SET_USERINFO", "");
            reject(e);
          });
      });
    },
    LogOut({ commit }) {
      commit("SET_TOKEN", "");
      commit("SET_USERINFO", {});
      removeToken();
    }
  }
};
export default user;
